Group Anagrams
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note:
- For the return value, each inner list's elements must follow the lexicographic order.
- All inputs will be in lower-case.
题目大意:给定一个字符串数组,将其分类,含有相同数量字母的为一类。要求每一类按字母序返回,所有输入为小写
题目难度:Medium
import java.util.*;
/**
* Created by gzdaijie on 16/5/23
* 不同的质数相乘,结果一定不同,可以用不同质数代替字母
* 判断乘积,即可以判断是否属于同一组,借助hashMap记录键值对
*/
public class Solution {
public static List<List<String>> groupAnagrams(String[] strs) {
int[] prime = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103};
List<List<String>> result = new ArrayList<>();
HashMap<Integer, Integer> hash = new HashMap<>();
for (String s : strs) {
int key = 1;
for (char ch: s.toCharArray()) {
key *= prime[ch - 'a'];
}
if (hash.containsKey(key)) {
result.get(hash.get(key)).add(s);
} else {
List<String> t = new ArrayList<>();
t.add(s);
result.add(t);
hash.put(key, result.size() - 1);
}
}
for (List list: result) {
Collections.sort(list);
}
return result;
}
}